package com.mspbots.rule.queue.producer;

import com.mspbots.api.service.SheetsTimesService;
import com.mspbots.api.service.TenantService;
import com.mspbots.cw.request.SheetsTimeDTO;
import com.mspbots.cw.request.TenantDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.stream.Collectors;

import static com.mspbots.rule.config.RuleConfiguration.REDIS_KEY_PREFIX_TENANT;

/**
 * @ClassName com.mspbots.rule.queue.producer.TsheetProducer
 * @Description TODO
 * @Author Jun
 * @Date 2019/9/2 16:40
 * @Version 1.0
 **/
@Slf4j
@Component
public class TsheetProducer {

    @Autowired
    SheetsTimesService sheetsTimesService;
    @Autowired
    TenantService tenantService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitMessagingTemplate messagingTemplate;

    //        @Scheduled(cron="0 0/1 * * * ?")
    public void produce() {
        log.info("TsheetProducer... {}", LocalDateTime.now());
        List<TenantDTO> tenantDTOS = redisTemplate.opsForList().range(REDIS_KEY_PREFIX_TENANT + "tenants", 0, -1);
        List<TenantDTO> tenantsActive = tenantDTOS.stream().filter(item -> item.getStatusId() == 1).collect(Collectors.toList());
        for (TenantDTO tenantDTO : tenantsActive) {
            Map<String, Object> params = new HashMap<>(16);
            params.put("tenantId", tenantDTO.getId());
//            params.put("lastModified", LocalDateTime.now());
            params.put("lastModified", LocalDateTime.of(2019, 9, 27, 12, 12, 12));
            Collection<SheetsTimeDTO> tSheetTimesS = sheetsTimesService.findList(params);
            if (!CollectionUtils.isEmpty(tSheetTimesS)) {
                Map<Long, SheetsTimeDTO> tSheetTimesMap = tSheetTimesS.stream().collect(Collectors.toMap(SheetsTimeDTO::getSheetUserId, item -> item, (k1, k2) -> k1));
                Iterator<Long> keyIterator = tSheetTimesMap.keySet().iterator();
                while (keyIterator.hasNext()) {
                    Long sheetUserId = keyIterator.next();
                    this.messagingTemplate.convertAndSend("msp.wise.sheet.times", "", tSheetTimesMap.get(sheetUserId));
//                    this.messagingTemplate.convertAndSend("msp.rule.topic", "trigger.tsheet.#", tSheetTimesMap.get(sheetUserId));
                }


            }


        }

    }

}
